//
//  FeedbackController.m
//  QQplayground
//
//  Created by zhangxy on 2018/8/8.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "FeedbackController.h"

#import "ZZDetailHeaderCell.h"
#import "ZZKeyboardView.h"
#import "ZZContentCommentController.h"

#import "FeedbackCell.h"
#define cellIdentifier @"FeedbackCell"
#import "ZZShareView.h"

@interface FeedbackController ()<ZZTopicCellDelegate>{
    int _page;
}

@property(nonatomic,strong)  NSMutableArray *listArray;
@property(nonatomic,strong)  UITableView *listTable;

@property(nonatomic,strong)  ZZDetailHeaderCell *headerCellView;
@property(nonatomic,strong)  ZZKeyboardView   *keyboardView;

@end

@implementation FeedbackController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"意见箱";
    [self setNavigationBar];
    
    
    self.navigationController.navigationBarHidden = NO;
    
    [self createTableView];
    
    
    
    _keyboardView = [[ZZKeyboardView alloc] initWithDelegate:self changeView:_listTable show:NO];
    _keyboardView.textField.placeholder = Uninput_opinion;
//    _keyboardView.chatpterModel = _entity;
    __weak FeedbackController *saveSelf = self;
    [_keyboardView setResultBlock:^(int code,NSString *text,id replayModel){
        if(code == 0){
            
            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
            [dict setObject:convertToString([UserUtil getUser].user_id) forKey:@"session_uid"];
            [dict setObject:convertToString(text) forKey:@"message"];
            [dict setObject:@"add" forKey:@"method"];
            if(replayModel!=nil){
                FeedBackEntity *tempModel = replayModel;
                [dict setObject:convertToString(tempModel.fid) forKey:@"quote_id"];
                [dict setObject:convertToString(tempModel.user_info.user_id) forKey:@"quote_uid"];
                [dict setObject:convertToString(tempModel.fid) forKey:@"id"];
            }else{
                [dict setObject:@"0" forKey:@"quote_id"];
                [dict setObject:@"0" forKey:@"quote_uid"];
            }
            
            [NetworkUtil POST:API_feedback_publish parameters:dict success:^(id responseObject, NSDictionary *dict) {
                FeedBackEntity *addModel = [[FeedBackEntity alloc] initWithDictionary:dict[@"data"]];
                addModel.user_info = [UserUtil getUser];
                [saveSelf.listArray insertObject:addModel atIndex:0];
                [saveSelf.listTable reloadData];
            } failure:^(NSError *error, NSString *message) {
                [PopUtil showMessage:message];
            }];
        }
    }];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
    
}



- (UIView *)headerView
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0)];
//    if(ZC_iPhoneX){
//        _headerCellView = [[NSBundle mainBundle]loadNibNamed:@"ZZDetailHeaderCell" owner:nil options:nil].firstObject;
//    }else{
//        _headerCellView = [[NSBundle mainBundle]loadNibNamed:@"ZZDetailHeaderCell" owner:nil options:nil].firstObject;
//    }
//    _headerCellView.delegate = self;
//    [_headerCellView dataToView:_entity];
//
//
//    //    UIImage *backImage =[UIImage imageNamed:@"voice_bg"];
//    //    headerView.layer.contents=(id)backImage.CGImage;
//    //    self.view.layer.backgroundColor = [UIColor clearColor].CGColor;
//    headerView.layer.backgroundColor = UIColor.clearColor.CGColor;
//    [headerView addSubview:_headerCellView];
    
    return headerView;
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [_keyboardView hideKeyboard];
}



-(void)createTableView{
    _listArray = [[NSMutableArray alloc] init];
    
    _listTable=[self.view createTableView:self cell:cellIdentifier formY:0 withHeight:self.view.bounds.size.height-BottomHeight];
    
    [_listTable setBackgroundColor:UIColorFromRGB(BgSystemColor)];
    
    if (iOS7) {
        _listTable.backgroundView = nil;
    }
    
    _listTable.tableHeaderView = [self headerView];
    
    [_listTable setSeparatorColor:LINE_COLOR];
    [_listTable setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    
    [self setTableSeparatorInset];
    
    MJRefreshBackStateFooter *footer = [MJRefreshBackStateFooter  footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    _listTable.footer = footer;
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [self loadBegin];
}

-(void)loadBegin{
    _page = 1;
    [self loadMoreData];
}


/**
 加载更多
 */
-(void)loadMoreData{
    [NetworkUtil POST:API_feedback_List parameters:@{@"page":convertIntToString(_page)} success:^(id responseObject, NSDictionary *dict) {
        DLog(@"responseObject:---%@", responseObject);
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
        if(_page == 1){
            [self.listArray removeAllObjects];
        }
        NSArray *arr = dict[@"data"][@"list"];
        for(NSDictionary *item in arr){
            if([item isKindOfClass:[NSDictionary class]]){
                
                FeedBackEntity *model = [[FeedBackEntity alloc] initWithDictionary:item];
                
                [self.listArray addObject:model];
            }
            
        }
        [self.listTable reloadData];
        if(convertToString(dict[@"data"][@"page"]).length>0){
//            if([dict[@"data"][@"page"] intValue] < [dict[@"data"][@"pages"] intValue]){
                self->_page = [dict[@"data"][@"page"] intValue] + 1;
//            }
        }
        
    } failure:^(NSError *error, NSString *message) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
//        [PopUtil showMessage:message];
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
    }];
}



#pragma mark UITableView delegate Start
// 返回section数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

// 返回section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1f;
}

// 返回section 的View
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 54)];
    [headerView setBackgroundColor:UIColor.whiteColor];
    return headerView;
}

// 返回section下得行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _listArray.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FeedbackCell *cell = (FeedbackCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[FeedbackCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.delegate = self;
    [cell dataToView:_listArray[indexPath.row]];
    
    return cell;
}



// 是否显示删除功能
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

// 删除清理数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}


// table 行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 70.0f;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// table 行的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
        FeedBackEntity *model=[_listArray objectAtIndex:indexPath.row];
    
    
}

//设置分割线间距
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if((indexPath.row+1) < _listArray.count){
        UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }
}

-(void)viewDidLayoutSubviews{
    [self setTableSeparatorInset];
}
#pragma mark UITableView delegate end

/**
 *  设置UITableView分割线空隙
 */
-(void)setTableSeparatorInset{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([_listTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_listTable setSeparatorInset:inset];
    }
    
    if ([_listTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_listTable setLayoutMargins:inset];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void)onCellItemClick:(ZZTopicCellClickType)type obj:(id)senderObj{
    [ZZCoreTools sucaiListenerImpl:senderObj type:type page:self refresh:_listTable];
}

@end
